package com.spring.use.controller;

import com.spring.use.R;
import com.spring.use.jms.MessageProducer;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * 模拟微信支付回调（rocketMQ 只要这个方法不抛出任何异常，就代表消息已经发送成功）
 */
@RestController
@RequestMapping("/api/v1")
public class TestController {

    @Value("${rocketmq.topic}")
    private String topic;
    @Value("${rocketmq.producer.group}")
    private String group;
    @Autowired
    private MessageProducer messageProducer;

    /**
     * 模拟微信支付回调
     * @param msg
     * @return
     */
    @GetMapping("/order")
    public R<SendResult> order(String msg){
        System.out.println("参数："+msg);
        //Destination destination = new ActiveMQQueue(queueName);
        //SendResult result = messageProducer.send(msg, topic, group);
        SendResult result = messageProducer.send(msg, topic, group,true);// 发送事务消息
        return R.ok(result);
    }

    /**
     * 多个生产者发送消息
     * @return
     */
    @GetMapping("/test-rocketmq/sendMsg")
    public R<SendResult> testSendMsg() {
        List<String> list=new ArrayList<>();
        list.add("1");
        list.add("2");
        list.add("3");
        SendResult result = messageProducer.send(list, topic, group);
        return R.ok(result);
    }

    /**
     * 发送异步消息
     * @param msg
     * @return
     */
    @GetMapping("/asyncSend")
    public R<SendResult> asyncSend(String msg){
        System.out.println("参数："+msg);
        // 异步发送消息到，主线程不会被阻塞，立刻会返回
        messageProducer.asyncSend(msg, topic, group,new SendCallback(){

            @Override
            public void onSuccess(SendResult sendResult) {
                // 消息发送成功，
            }

            @Override
            public void onException(Throwable throwable) {
                // 消息发送失败，可以持久化这条数据，后续进行补偿处理
            }
        });

        return R.ok();
    }
}
